package xps.and.uudaijia.userclient.view.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jude.utils.JUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Subscriber;
import xps.and.uudaijia.userclient.Constants;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.data.baen.LoginBean;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.util.AppCommond;
import xps.and.uudaijia.userclient.view.MainActivity;
import xps.and.uudaijia.userclient.view.base.BaseActivity;

public class LoginActivity extends BaseActivity {
    @BindView(R.id.Cell_phone_number)
    EditText CellPhoneNumber;
    @BindView(R.id.Login_Password)
    EditText LoginPassword;
    @BindView(R.id.Remember_password)
    CheckBox RememberPassword;
    @BindView(R.id.Sign_in)
    Button SignIn;
    @BindView(R.id.Login_Register)
    TextView LoginRegister;
    @BindView(R.id.Forgot_Password)
    TextView ForgotPassword;
    String CellPhoneString;
    String LoginPasswordString;
    String loginMethod = "basic";
    private static final String PREFS_NAME = "MyUserInfo";
    @BindView(R.id.Login_WeCont)
    ImageView LoginWeCont;
    private IWXAPI api;


    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void setData() {
    }

    @Override
    protected void init() {
        ButterKnife.bind(this);
        LoadUserDate();
        Intent i = getIntent();
        if (i.getStringExtra("zhanghao") != null) {
            if (i.getStringExtra("zhanghao").equals("1")) {
                showCustomize();
            }
        }
        if (!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
    }

    @OnClick({R.id.Login_Register, R.id.Forgot_Password, R.id.Sign_in, R.id.Login_WeCont})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.Login_Register:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.Forgot_Password:
                Intent UpPasswordintent = new Intent(LoginActivity.this, UpPasswordActivity.class);
                startActivity(UpPasswordintent);
                break;
            case R.id.Sign_in:
                CellPhoneString = CellPhoneNumber.getText().toString();
                LoginPasswordString = LoginPassword.getText().toString();
                Login();
                showDialogNoCancel();
                SaveUserDate();
                break;
            case R.id.Login_WeCont:
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                api.sendReq(req);
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppCommond a) {
        if (!AppCommond.check(a)) return;
        for (String activityName : a.getAcNameList()) {
            if (activityName.equals(getClass().getSimpleName())) {
                unreg();
                finish();
                break;
            }
        }
    }

    void unreg() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unreg();
    }

    void Login() {
        UserNetWorks.getLogin(loginMethod, CellPhoneString, LoginPasswordString, new Subscriber<LoginBean>() {
            @Override
            public void onCompleted() {
                dissmisDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onNext(LoginBean loginBean) {
                LoginBean.ReturnBodyBean returnBodyBean = loginBean.getReturn_body();
                if (loginBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast("登陆成功");
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("access_token", returnBodyBean.getAccess_token());
                    intent.putExtra("userId", returnBodyBean.getUserId() + "");
                    SharedPreferences sp = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd = sp.edit();
                    spEd.putString("User_Access_token", returnBodyBean.getAccess_token());
                    spEd.putString("User_ID", returnBodyBean.getUserId() + "");
                    spEd.putString("User_name", returnBodyBean.getName() + "");
                    spEd.putString("User_Phone", returnBodyBean.getUserPhone() + "");
                    spEd.putString("User_Img", returnBodyBean.getHeadImg() + "");
                    spEd.putBoolean("User_Login", true);
                    spEd.putString("YHJ", "");
                    spEd.commit();
                    startActivity(intent);
                    JPushInterface.setAliasAndTags(LoginActivity.this, returnBodyBean.getAccess_token().substring(0, 10), null, mAliasCallback);
                    finish();
                } else if (loginBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(loginBean.getReturn_msg());
                }
            }
        });
    }

    private void SaveUserDate() {
        // 载入配置文件
        SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);
        // 写入配置文件
        SharedPreferences.Editor spEd = sp.edit();
        if (RememberPassword.isChecked()) {
            spEd.putBoolean("isSave", true);
            spEd.putString("name", CellPhoneNumber.getText().toString());
            spEd.putString("password", LoginPassword.getText().toString());
        } else {
            spEd.putBoolean("isSave", false);
            spEd.putString("name", "");
            spEd.putString("password", "");
        }
        spEd.commit();
    }

    private void LoadUserDate() {
        SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);

        if (sp.getBoolean("isSave", false)) {
            String username = sp.getString("name", "");
            String userpassword = sp.getString("password", "");
            if (!("".equals(username) && "".equals(userpassword))) {
                CellPhoneNumber.setText(username);
                LoginPassword.setText(userpassword);
                RememberPassword.setChecked(true);
            }
        }
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success极光推送别名设置成功";
                    Log.i("mAliasCallback", logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.极光推送别名设置失败，60秒后重试";
                    Log.i("mAliasCallback", logs);
                    break;
                default:
                    logs = "极光推送设置失败，Failed with errorCode = " + code;
                    Log.e("mAliasCallback", logs);
                    break;
            }
        }
    };


    public void showCustomize() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(LoginActivity.this);
        final View dialogView = LayoutInflater.from(LoginActivity.this)
                .inflate(R.layout.dialog_dianhua, null);
        TextView textView = (TextView) dialogView.findViewById(R.id.edit_text);
        textView.setText("您的账号在其他地方登录");
        customizeDialog.setTitle("温馨提示");
        customizeDialog.setView(dialogView);
        customizeDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        // CloseActivityClass.exitClient(LoginActivity.this);
                        dialog.dismiss();
                    }
                });
        customizeDialog.show();
    }
}